//
// Created on 2025/7/25.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef STREAMCORE_SAFE_FILE_HANDLE_H
#define STREAMCORE_SAFE_FILE_HANDLE_H
#include <string>
#include <sys/stat.h>

enum class FileMode { CreateNew = 1, Create = 2, Open = 3, OpenOrCreate = 4, Truncate = 5, Append = 6 };
enum class FileAccess { Read = 1, ReadWrite = 2, Write = 3 };
enum class FileShare { None = 0, Read = 1, Write = 2, ReadWrite = 3, Delete = 4, Inheritable };
/**
 * RAII包装fd
 */
class SafeFileHandle {
public:
    explicit SafeFileHandle(std::string path, FileMode mode, FileAccess access, FileShare share);
    ~SafeFileHandle();

    // 禁用拷贝
    SafeFileHandle(const SafeFileHandle &) = delete;
    SafeFileHandle &operator=(const SafeFileHandle &) = delete;

    // 移动语义
    SafeFileHandle(SafeFileHandle &&other) noexcept;
    SafeFileHandle &operator=(SafeFileHandle &&other) noexcept;

    // 显式转换
    explicit operator bool() const noexcept { return fd_ != -1; }

    // 访问器
    int fd() const noexcept { return fd_; }
    const std::string &path() const noexcept { return path_; }

    void write(const void *buf, size_t len);
    long read(void *buf, size_t len);
    size_t seek(long offset, int origin);
    void flush();


    bool canSeek() const { return canSeek_; }
    bool canRead() const { return fd_ != -1 && access_ != FileAccess::Write; }
    bool canWrite() const { return fd_ != -1 && access_ != FileAccess::Read; }
    size_t length() const { return length_; }
    size_t position() const { return position_; }

    void setLength(size_t length);

private:
    void release();
    void lock(int locktype);
    void unlock();

    int fd_;
    std::string path_;
    bool is_locked_;
    bool delete_on_close_;
    size_t length_;
    size_t position_;
    long append_start_;
    bool canSeek_;
    FileAccess access_;
};
#endif // STREAMCORE_SAFE_FILE_HANDLE_H
